package concurrent.thread;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import javax.servlet.http.HttpServletRequest;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2021-07-15 09:39:00
 */
public class ThreadLocalDemo {

    private static LuThreadLocal<User> threadLocal = new LuThreadLocal();

    public static void main(String[] args) {
        String inParams = "asdad";
        String res = threadLocal.functionProxy(x -> {
            System.out.println(JSON.toJSONString(threadLocal.local.get()));
            return inParams + 1;
        }, y -> {
            threadLocal.local.set(User.builder().name("lu").age(24).build());
        });
        System.out.println(res);
    }

}

@Data
@Accessors(chain = true)
@Builder
@AllArgsConstructor
@NoArgsConstructor
class User{
    private String name;
    private Integer age;
}


class LuThreadLocal<S>{

    ThreadLocal<S> local = new ThreadLocal<>();

    public <T, R> R functionProxy(Function<T, R> func, Consumer<HttpServletRequest> consumer){
        consumer.accept(null);
        R res = func.apply(null);
        local.remove();
        return res;
    }

}
